package com.student.manage.aop;


import com.student.manage.annotation.RepeatSubmit;
import com.student.manage.util.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

@Aspect
@Component
@Slf4j
public class RepeatSubmitAspect {

    public static final String REPEAT_SUBMIT = "repeat_code";

    public RepeatSubmitAspect() {
        log.info("RepeatSubmitAspect");
    }


    public static void main(String[] args) {
        String uriString = UriComponentsBuilder.fromUriString("/user/edit.html").queryParam("id", "123").build().toUriString();
        System.out.println(uriString);
    }

    @Pointcut("execution(* com.student.manage.controller.*.*(..)) && @annotation(repeatSubmit)")
    public void pointcut(RepeatSubmit repeatSubmit) {
    }

    @Around("pointcut(repeatSubmit)")
    public Object around(ProceedingJoinPoint point, RepeatSubmit repeatSubmit) throws Throwable {
        String fallback = repeatSubmit.fallback();
        String[] paramNames = repeatSubmit.paramNames();

        String repeatCode = HttpServletUtil.getSessionAttribute(REPEAT_SUBMIT);
        String parameterCode = HttpServletUtil.getRequest().getParameter(REPEAT_SUBMIT);

        if (!StringUtils.hasText(parameterCode)) {
            return "error";
        }
        if (StringUtils.hasText(repeatCode) && repeatCode.equals(parameterCode)) {
            // 是第一次提交
            log.info("第一次提交");
            Object result = point.proceed(point.getArgs());
            HttpServletUtil.removeSessionAttribute(REPEAT_SUBMIT);
            return result;
        }
        // 说明重复提交
        if (StringUtils.hasText(fallback)) {

            if (CollectionUtils.isEmpty(List.of(paramNames))) {
                return fallback;
            }

            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(fallback);

            for (String paramName : paramNames) {
                builder.queryParam(paramName, HttpServletUtil.getRequest().getParameter(paramName));
            }
            
            return builder.build().toUriString();
        } else {
            String referer = HttpServletUtil.getRequest().getHeader("referer");
            if (referer != null) {
                return "redirect:" + referer;
            }
        }

        return "error";


    }

}
